﻿using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;

/// <summary>
/// 自动填充并且实例化指定 layout 的 Cell元素
/// </summary>
[DefaultExecutionOrder(-1)]
public class UILayoutFill : MonoBehaviour
{
    [Tooltip("填充Cell的最大数量")]
    public int maxCount = 8;
    public GameObject prefab;

    public bool fillAwake = true;

    private void Awake()
    {
        if (fillAwake) FillChild(this.maxCount);
    }

    public void FillChild(int maxCount)
    {
        int total = maxCount;
        if (prefab == null)
        {
            prefab = transform.GetChild(0).gameObject;
        }

        if (prefab == null)
        {
            Debug.LogError("Need set a prefab Gameobject for" + gameObject.name);
            return;
        }

        int offset = total - this.transform.childCount;
        if (offset > 0)
        {
            for (int i = 0; i < offset; i++)
            {
                var obj = Instantiate(prefab);
                obj.name = obj.name.Replace("(Clone)", "");
                obj.transform.SetParent(transform, false);
            }
        }
        else
        {
            for (int i = 0; i < this.transform.childCount; i++)
            {
                this.transform.GetChild(i).gameObject.SetActive(i < maxCount);
            }
        }

    }

    /// <summary>
    /// 遍历所有已激活子对象，执行callback
    /// </summary>
    /// <param name="callback"></param>
    public void ForEachChild(Action<int, Transform> callback)
    {
        int index = 0;
        foreach (Transform item in this.transform)
        {
            if (item.gameObject.activeSelf)
            {
                callback?.Invoke(index, item);
                index++;
            }

        }
    }



}
